package models

import (
	"fmt"
	contractsorm "github.com/goravel/framework/contracts/database/orm"
	"github.com/goravel/framework/database/orm"
	"github.com/goravel/framework/facades"
)

type Kind struct {
	orm.Model
	Pid       uint   `gorm:"column:pid" form:"pid" json:"pid"`
	Name      string `gorm:"type:varchar(255);not null;" form:"name" json:"name"`
	UnionName string `gorm:"type:varchar(255);not null;" form:"union_name" json:"union_name"`
	Children  []Kind `gorm:"foreignKey:pid;references:ID;" form:"children" json:"children"`
	orm.SoftDeletes
}

func (u *Kind) DispatchesEvents() map[contractsorm.EventType]func(contractsorm.Event) error {
	return map[contractsorm.EventType]func(contractsorm.Event) error{
		contractsorm.EventCreated: func(event contractsorm.Event) error {
			p_kind := Kind{}
			query := facades.Orm().Query()
			query.Model(&Kind{}).Where("id=?", u.Pid).First(&p_kind)
			if p_kind.ID != 0 {
				query.Model(&Kind{}).Where("id=?", u.ID).Update("union_name", fmt.Sprintf("%s-%s", p_kind.UnionName, u.Name))
			} else {
				query.Model(&Kind{}).Where("id=?", u.ID).Update("union_name", fmt.Sprintf("%s", u.Name))
			}
			return nil
		},
		contractsorm.EventUpdated: func(event contractsorm.Event) error {
			p_kind := Kind{}
			query := facades.Orm().Query()
			query.Model(&Kind{}).Where("id=?", u.Pid).First(&p_kind)
			if p_kind.ID != 0 {
				query.Model(&Kind{}).Where("id=?", u.ID).Update("union_name", fmt.Sprintf("%s-%s", p_kind.UnionName, u.Name))
			} else {
				query.Model(&Kind{}).Where("id=?", u.ID).Update("union_name", fmt.Sprintf("%s", u.Name))
			}
			return nil
		},
	}
}
